package com.xuexuehai.carrecommand.controller;

import com.xuexuehai.carrecommand.dto.HttpResp;
import com.xuexuehai.carrecommand.entity.Privs;
import com.xuexuehai.carrecommand.entity.User;
import com.xuexuehai.carrecommand.exception.enums.SysStatusEnums;
import com.xuexuehai.carrecommand.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xuexuehai
 * @mailBox xuehai.xue@QQ.com
 * @date 2021/8/19 9:02 上午
 */

@RestController
@RequestMapping("/api/user")
@Api(tags = "用户模块")
@CrossOrigin
public class UserController {
    @Autowired
    private IUserService ius;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/login")
    @ApiOperation("用户登录")
    public HttpResp login(String username, String password) {
        //使用UserService中的login方法登录用户并且获取用户权限
        List<Privs> privs = ius.login(username, password);

        //在缓存中添加用户的权限,使用用户的登录名称作为redis缓存的key，将权限保存在key的value中
        redisTemplate.opsForValue().set(username, privs);

        //给前端返回登录结果
        return new HttpResp(SysStatusEnums.LOGIN_SUCCESS.getCode(),
                SysStatusEnums.LOGIN_SUCCESS.getMsg(),
                username, null);
    }

    @PutMapping("/registryUser")
    @ApiOperation("用户注册")
    public HttpResp registryUser(User user){
        ius.registerUser(user);
        return new HttpResp(SysStatusEnums.REGISTRY_SUCCESS.getCode(),
                SysStatusEnums.REGISTRY_SUCCESS.getMsg(),
                null, null);
    }
}
